<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="发送者" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入发送者"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createName">
        <el-input
          v-model="queryParams.createName"
          placeholder="请输入创建时间"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属项目ID" prop="projectId">
        <el-input
          v-model="queryParams.projectId"
          placeholder="请输入所属项目ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['project:notice:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['project:notice:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['project:notice:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['project:notice:export']"
        >导出</el-button>
        </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="openChart"
          v-hasPermi="['project:notice:add']"
        >统计</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="noticeList" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="通知ID" align="center" prop="noticeId" :sort-orders="['descending','ascending']" sortable="custom"/>
      <el-table-column label="发送者" align="center" prop="username" :sort-orders="['descending','ascending']" sortable="custom"/>
      <el-table-column label="创建时间" align="center" prop="createName" :sort-orders="['descending','ascending']" sortable="custom"/>
      <el-table-column label="通知内容" align="center" prop="content" />
      <el-table-column label="所属项目ID" align="center" prop="projectId" :sort-orders="['descending','ascending']" sortable="custom"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['project:notice:detail']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['project:notice:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['project:notice:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改通知信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="发送者" prop="username">
          <el-input v-model="form.username" placeholder="请输入发送者" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createName">
          <el-input v-model="form.createName" placeholder="请输入创建时间" />
        </el-form-item>
        <el-form-item label="通知内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="所属项目ID" prop="projectId">
          <el-input v-model="form.projectId" placeholder="请输入所属项目ID" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog
      title="通知详情"
      :visible.sync="isDetail"
      width="50%"
    >
      <div>
        <p><strong>通知ID：</strong>{{ form.noticeId }}</p>
        <p><strong>发送者：</strong>{{ form.username }}</p>
        <p><strong>创建时间：</strong>{{ form.createName }}</p>
        <p><strong>所属项目ID：</strong>{{ form.projectId }}</p>
        <p><strong>通知内容：</strong>{{ form.content }}</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isDetail = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 统计弹窗 -->
    <el-dialog
      title="通知统计图表"
      :visible.sync="chartVisible"
      width="80%"
      @close="resetChart"
    >
      <div>
        <!-- 饼状图 -->
        <div ref="pieChart" style="width: 50%; height: 400px; display: inline-block;"></div>
        <!-- 柱状图 -->
        <div ref="barChart" style="width: 50%; height: 400px; display: inline-block;"></div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listNotice, getNotice, delNotice, addNotice, updateNotice } from "@/api/project/notice";
import * as echarts from 'echarts';

export default {
  name: "Notice",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 通知信息表格数据
      noticeList: [],
      chartList:{},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      isDetail: false,
      chartVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        username: null,
        createName: null,
        content: null,
        projectId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        username: [
          { required: true, message: "发送者不能为空", trigger: "blur" }
        ],
        createName: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "通知内容不能为空", trigger: "blur" }
        ],
        projectId: [
          { required: true, message: "所属项目ID不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /**统计*/
    openChart() {
      const chartList = {};
      this.noticeList.forEach(item => {
        chartList[item.projectId] = (chartList[item.projectId] || 0) + 1;
      });

      this.chartList = chartList;
      this.chartVisible = true;
      this.$nextTick(() => {
        this.drawCharts();
      });
    },
    drawCharts() {
      const labels = Object.keys(this.chartList);
      const values = Object.values(this.chartList);

      // 饼状图配置
      const pieChart = this.$refs.pieChart;
      const pieOption = {
        title: {
          text: '通知统计饼状图',
          subtext: '按 项目 分类',
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)',
        },
        series: [
          {
            name: '通知统计',
            type: 'pie',
            radius: '55%',
            center: ['50%', '50%'],
            data: labels.map((label, index) => ({
              value: values[index],
              name: label,
            })),
          },
        ],
      };
      // 初始化并渲染饼状图
      const pieChartInstance = echarts.init(pieChart);
      pieChartInstance.setOption(pieOption);

      // 柱状图配置
      const barChart = this.$refs.barChart;
      const barOption = {
        title: {
          text: '通知统计柱状图',
          subtext: '按 项目 分类',
          left: 'center',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
        },
        xAxis: {
          type: 'category',
          data: labels,
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            name: '数量',
            type: 'bar',
            data: values,
          },
        ],
      };
      // 初始化并渲染柱状图
      const barChartInstance = echarts.init(barChart);
      barChartInstance.setOption(barOption);
    },
    // 在关闭弹窗时重置图表
    resetChart() {
      this.chartList = {}; // 重置 chartList
      this.$nextTick(() => {
        // 清除图表实例
        const pieChartInstance = echarts.getInstanceByDom(this.$refs.pieChart);
        if (pieChartInstance) pieChartInstance.dispose();

        const barChartInstance = echarts.getInstanceByDom(this.$refs.barChart);
        if (barChartInstance) barChartInstance.dispose();
      });
    },

    /** 查询通知信息列表 */
    getList() {
      this.loading = true;
      listNotice(this.queryParams).then(response => {
        this.noticeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        noticeId: null,
        username: null,
        createName: null,
        content: null,
        projectId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.noticeId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加通知信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const noticeId = row.noticeId || this.ids
      getNotice(noticeId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改通知信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.noticeId != null) {
            updateNotice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addNotice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const noticeIds = row.noticeId || this.ids;
      this.$modal.confirm('是否确认删除通知信息编号为"' + noticeIds + '"的数据项？').then(function() {
        return delNotice(noticeIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('project/notice/export', {
        ...this.queryParams
      }, `notice_${new Date().getTime()}.xlsx`)
    },
    /** 监听函数 */
    handleSortChange(column) {
      this.queryParams.orderByColumn = column.prop;//查询字段是表格中字段名字
      this.queryParams.isAsc = column.order;//动态取值排序顺序
      this.getList();
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      const noticeId = row.noticeId || this.ids
      getNotice(noticeId).then(response => {
        this.form = response.data;
      });
      this.isDetail = true; // 打开详情弹窗
    },
    /** 饼状图按钮操作 */
    noticebing() {
      this.$router.replace({name:'noticepie'})
    },
  }
};
</script>
